package net.hhk.connect;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import net.hhk.data.Constant;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.widget.Toast;

public class HTTPConnect {
	public String URL;
	public List<NameValuePair> postParameters;
	private static HttpClient httpClient ;
	public static HTTPConnect http; 

//	public HTTPConnect(String url,List<NameValuePair> post) {
//		URL = "http://192.168.1.38/"+url;
//		this.postParameters = post;
//	}
	public HTTPConnect(){
		//httpClient = new DefaultHttpClient();
	}
	public String doConnect(String url,List<NameValuePair> post) {
		BufferedReader bufferedReader = null;
		httpClient = HttpClientFactory.getThreadSafeClient();
		url = Constant.HOST+url;
		HttpPost request = new HttpPost(url);
//		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//		postParameters.add(new BasicNameValuePair("p", "Android"));
		StringBuffer stringBuffer = new StringBuffer("");
		String line = "";


		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
					post);
			request.setEntity(entity);

			HttpResponse response = httpClient.execute(request);

			bufferedReader = new BufferedReader(new InputStreamReader(response
					.getEntity().getContent()));
						String LineSeparator = System.getProperty("line.separator");
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line + LineSeparator);
			}
			bufferedReader.close();

			// result.setText(stringBuffer.toString());

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// Toast.makeText(AndroidHttpPostActivity.this,
			// e.toString(),
			// Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// Toast.makeText(AndroidHttpPostActivity.this,
			// e.toString(),
			// Toast.LENGTH_LONG).show();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return stringBuffer.toString();

	}
	public static HTTPConnect getConnect(){
		if(http == null){
			http =new HTTPConnect();
		}
		return http;
	}
}
